package com.elem.dao.impl;

import com.elem.bean.Orders;
import com.elem.dao.OrdersDao;
import com.elem.util.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class OrdersDaoImpl implements OrdersDao {
    // 创建JdbcTemplate对象
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public int createOrders(Orders orders) throws Exception {

        String sql = "INSERT INTO orders(userId, businessId, orderDate, orderTotal, daId, orderState) VALUES(?,?,?,?,?,?)";

        KeyHolder keyHolder = new GeneratedKeyHolder();
        /*
        *
        *  匿名内部类的写法
        * */
        jdbcTemplate.update(new PreparedStatementCreator() {
            PreparedStatement ps = null;
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {

                ps = con.prepareStatement(sql,new String[]{"orderId"});
                ps.setString(1,orders.getUserId());
                ps.setInt(2,orders.getBusinessId());
                ps.setString(3,orders.getOrderDate());
                ps.setDouble(4,orders.getOrderTotal());
                ps.setInt(5,orders.getDaId());
                ps.setInt(6,orders.getOrderState());

                return ps;
            }
        },keyHolder);


        int orderId = keyHolder.getKey().intValue();
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) throws Exception {
        String sql = "SELECT * FROM orders WHERE orderId = ?";
        Orders orders = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Orders>(Orders.class), orderId);
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) throws Exception {
        String sql = "select * from orders where userId = ?";
        List<Orders> ordersList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Orders.class), userId);
        return ordersList;
    }
}
